package es.unex.meigas.ww.core;

import java.io.IOException;
import java.util.Iterator;

import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.dbf.DbaseFileReader;
import org.geotools.data.shapefile.dbf.DbaseFileReader.Row;
import org.opengis.feature.simple.SimpleFeature;

import es.unex.meigas.dataObjects.IRecord;
import es.unex.meigas.dataObjects.IRecordsetIterator;
import es.unex.meigas.dataObjects.RecordImpl;
import es.unex.meigas.exceptions.IteratorException;


public class WWRecordsetIterator implements IRecordsetIterator {

	private Object m_Iter;

    public WWRecordsetIterator(Object obj){

    	try{
    		if (obj instanceof FeatureSource){
    			FeatureSource fs = (FeatureSource) obj;
    			m_Iter = fs.getFeatures().iterator();

    		}
    		else if (obj instanceof DbaseFileReader){
    			DbaseFileReader dbf = (DbaseFileReader) obj;
    			m_Iter =  obj;
    		}
    	}
    	catch(Exception e){}


    }

    public boolean hasNext() {

    	if (m_Iter != null){
    		if (m_Iter instanceof Iterator){
    			Iterator iter = (Iterator) m_Iter;
    			return iter.hasNext();
    		}
    		else if (m_Iter instanceof DbaseFileReader){
    				DbaseFileReader dbf = (DbaseFileReader) m_Iter;
    				return dbf.hasNext();
    		}
    		else{
    			return false;
    		}
    	}
    	else{
    		return false;
    	}

    }

    public IRecord next() throws IteratorException{

    	if (m_Iter != null){
        	if (!hasNext()){
        		throw new IteratorException();
        	}
    		if (m_Iter instanceof Iterator){
    			Iterator iter = (Iterator) m_Iter;
    			SimpleFeature gtFeat = (SimpleFeature) iter.next();
        		Object values[] = new Object[gtFeat.getAttributeCount()];
        		for (int i = 0; i < gtFeat.getAttributeCount(); i++) {
        			values[i] = gtFeat.getAttribute(i);
    			}
        		IRecord rec = new RecordImpl(values);
        		return rec;
    		}
    		else if (m_Iter instanceof DbaseFileReader){
    			DbaseFileReader dbf = (DbaseFileReader) m_Iter;
    			try {
					Row row = dbf.readRow();
					int iNumFields = dbf.getHeader().getNumFields();
					Object values[] = new Object[iNumFields];
					for (int i = 0; i < iNumFields; i++) {
						values[i] = row.read(i);
					}
					IRecord rec = new RecordImpl(values);
	        		return rec;
				} catch (IOException e) {
					throw new IteratorException();
				}
    		}
    		else{
    			throw new IteratorException();
    		}

    	}
    	else{
    		throw new IteratorException();
    	}

    }

	public void close() {


	}



}
